package handler

import (
	"github.com/gin-gonic/gin"
	"mock-exam2/model"
	"strconv"
)

func GoodAdd(c *gin.Context) {
	goodname := c.PostForm("goodname")
	goodprice, _ := strconv.Atoi(c.PostForm("goodprice"))
	stock, _ := strconv.Atoi(c.PostForm("stock"))
	if goodname == "" || goodprice == 0 || stock == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "请将商品信息填写完整",
		})
		return
	}
	good := model.Good{
		Goodname:  goodname,
		GoodPrice: goodprice,
		Stock:     stock,
	}
	model.DB.Create(&good)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "商品信息添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	customer := c.PostForm("customer")
	orderprice, _ := strconv.Atoi(c.PostForm("orderprice"))
	if gid == 0 || orderprice == 0 || customer == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "请将订单信息填写完整",
		})
		return
	}
	order := model.Order{
		Gid:        gid,
		Customer:   customer,
		OrderPrice: orderprice,
	}
	model.DB.Create(&order)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单信息添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var goodorder []model.GoodOrder
	model.DB.Table("orders").
		Select(
			"goods.goodname as GoodName",
			"goods.good_price as GoodPrice",
			"goods.stock as Stock",
			"orders.id as Oid",
			"orders.customer as Customer",
			"orders.order_price as OrderPrice",
		).
		Joins("left join goods on orders.gid = goods.id").
		Offset(offset).
		Limit(size).
		Find(&goodorder)
	var total int64
	model.DB.Model(goodorder).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"total": total,
		"data":  goodorder,
	})
	return
}
